<template>
    <div class="basic-container mt-50 mb-50">
        <div ref="searchRef" class="search">
            <n-input @input="handleSearch" v-model:value="searchValue" type="text" placeholder="内容搜索" clearable />
        </div>

        <div class="tabs">
            <n-divider />
            <n-tabs @update:value="handleTabs" :default-value="tabValue" type="segment" animated>

                <n-tab-pane v-for="item in classify" :key="item.id" :tab="item.title" :name="item.id">
                    <!-- <n-spin :show="show"> -->
                    <div ref="tabRef" class="scroll-box">
                        <section class="content-box" :class="{ 'bg-active': content.isTopping }"
                            v-for="(content, index) in item.content" :key="content.id">
                            <div class="row-main">
                                <div @click="handleOpen(content.id, index)" class="main-title">
                                    <div v-html="content.title" class="title"></div>
                                </div>
                                <div @click="handleOpen(content.id, index)" class="main-box">
                                    <div class="left-text">
                                        <div v-text="content.text" class="text"></div>
                                    </div>
                                    <div v-if="content.imageUrl" @click="handleOpen(content.id, index)"
                                        class="right-img">
                                        <img :src="content.imageUrl" alt="什么几把网" sizes="" srcset="">
                                        <!-- data:image/png;base -->
                                    </div>
                                </div>
                                <ul class="action-list mt-3">
                                    <li class="user-name item">{{ content.noteUsername }}</li>
                                    <i class="iconfont icon-yanjing"></i>
                                    <li class="view item"> {{ content.see }}</li>
                                    <i @click="handleLike(content)" class="iconfont icon-icon-thumbsUp22"></i>
                                    <li class="like item">{{ content.like === 0 ? '赞同' : content.like }}</li>
                                    <li class="time item">{{ formatTime(new Date(content.createTime)) }}</li>
                                </ul>
                            </div>
                        </section>
                    </div>


                    <footer v-if="item.content.length === 0" class="center">
                        <n-result status="404" title="大！大！啊" description="看看别的呢" size="huge">
                            <template #footer>
                                <n-button>哦</n-button>
                            </template>
                        </n-result>
                    </footer>
                    <!-- </n-spin> -->
                </n-tab-pane>

            </n-tabs>
        </div>
    </div>
</template>

<script setup lang="ts">
import debounce from 'lodash/debounce';
// @ts-ignore
import { getNoteFormList, likeUpdate } from '@/apis/index';
import { formatTime } from '@/utils/index';
import bus from '@/utils/mitt';

const loadingBar = useLoadingBar()
const tabRef: any = ref('');
let currentHeightNum = ref(0);
const searchRef: any = ref('');
const message = useMessage()

interface Content {
    id: number | string;
    title: string;
    text: string;
    see: number;
    noteUsername: string;
    createTime: string;
    like: number;
    isTopping: boolean,
    imageUrl?: string;
}


interface Classify {
    title: string;
    id: number;
    content: Content[]
}
const router = useRouter();
let searchValue = ref('');
let tabValue = ref(1);

const classify = reactive<Classify[]>([
    {
        title: '日常',
        id: 1,
        content: []
    },
    {
        title: '推荐',
        id: 2,
        content: []
    },
    {
        title: '待办',
        id: 3,
        content: []
    }
]);



const debounceSearch = debounce(() => {
    filterClassify();
}, 1000)

function filterClassify() {
    obtainNoteFormList(searchValue.value);
    classify.forEach((item) => {
        item.content.forEach((content) => {
            // 正则表达式匹配标题
            const regex = new RegExp(searchValue.value, 'gi');
            const match = content.title.match(regex);
            if (match) {
                content.title = content.title.replace(regex, `<span style="color: red">${match[0]}</span>`);
            }
        })
    })


}

function handleSearch(val: string) {
    if (val === '') {
        classify.forEach((item) => {
            item.content.forEach((content) => {
                content.title = content.title.replace(/<span style="color: red">(.*?)<\/span>/g, '$1');
            })
            return;
        })
    }
    debounceSearch();

}

function handleTabs(val: number) {
    tabValue.value = val;
}

function handleOpen(id: number | string, index: number) {
    sessionStorage.setItem('index', index + '');
    // 将字符串以句号或者空格切割为数组但逗号不需要处理
    // const currentData: any = classify[0].content[index];
    // let splitContent = currentData.text.split(/[。|\n]/);
    // splitContent = splitContent.filter((item: string) => item !== '');
    // // 模拟详情页数据
    // const mockDetails: any = {
    //     title: currentData.title,
    //     html: splitContent,
    //     avatarName: currentData.noteUsername,
    //     imageUrl: currentData.imageUrl ?? '',
    //     createTime: currentData.createTime,
    //     content: currentData.text,
    //     comment: [],
    // }
    // sessionStorage.setItem('detail-testData', JSON.stringify(mockDetails));
    router.push({
        path: '/detail',
        query: {
            id: id,
            height: currentHeightNum.value
        }
    })

}

// 前端上传图片 -》 服务器拿到图片文件存
function handleLike(item: Content) {
    item.like++;
    likeUpdate({ noteId: item.id })
}



// 推荐
function recommend(data: any) {
    let arr = JSON.parse(data);
    // 浏览量排序
    arr.sort((a: any, b: any) => {
        return b.see - a.see
    })
    // 推荐
    return arr;
    // classify[1].content = recommendData
}

let loading = ref(false) // 搜索｜ 查询
async function obtainNoteFormList(value: string) {
    loadingBar.start();
    loading.value = false;
    await getNoteFormList({ search: value }).then((res: any) => {
        if (res.status == 200) {
            let currentData = res.data;
            const routineData = currentData.filter((item: any) => item.isTopping === false);
            const toppingData = currentData.filter((item: any) => item.isTopping);
            currentData = [...toppingData, ...routineData]
            classify[0].content = currentData;
            classify[1].content = recommend(JSON.stringify(res.data));
            loading.value = true;
            loadingBar.finish();

        }
    }).catch(err => {
        message.error(err.data.message)
        loading.value = false;
        loadingBar.error();
    })
    scrollHander();
}

function scrollHander() {
    currentHeightNum.value = window.scrollY;
    if (window.scrollY > 200) {
        searchRef.value.style.top = '-50px'
    } else {
        searchRef.value.style.top = '0px'
    }
}

// 更新动态
function classifyActive() {
    nextTick(() => {
        const index = Number(sessionStorage.getItem('index'))
        const list = document.querySelectorAll('.content-box')
        list[index].classList.add('active-row');
        setTimeout(() => {
            list[index].classList.remove('active-row');
        }, 1000);
    })
}
onBeforeUnmount(() => {
    searchRef.value.style.top = '0px'
    window.removeEventListener('scroll', scrollHander)
})

onMounted(async () => {
    await obtainNoteFormList('')
    if (loading.value) {
        bus.on('update-content', (e: any) => {
            nextTick(() => {
                setTimeout(() => {
                    window.scrollTo({
                        top: Number(e.height),
                        behavior: "smooth"
                    })
                    classifyActive()
                }, 1500);
            })
        })
    }
    window.addEventListener('scroll', scrollHander);
})

</script>


<style lang="scss" scoped>
.search {
    padding: 0 20px 0 20px;
    margin-top: 8px;
    width: 100%;
    position: fixed;
    top: 0;
    z-index: 999;
    transition: all 0.5s;

    .n-input {
        width: calc(100% - 40px);
        ;
        border-radius: 2px;
    }
}

.scroll-box {
    background-color: #f2f3f4;
}


.content-box {
    padding: 12px 16px 0;
    position: relative;
    background: #fff;
    // padding: 16px 20px 0;
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    margin-bottom: 8px;


    .row-main {
        width: 100%;
        padding-bottom: 16px;
        display: flex;
        flex-direction: column;
        cursor: pointer;

        .action-list {
            display: flex;
            align-items: center;

            i {
                margin-top: -2px;
                margin-right: 3px;
            }

            .item {
                margin-right: 20px;
                font-size: 13px;
                color: #8A919F;
            }
        }
    }

    .main-title .title {
        margin: 4px 0;
        font-weight: 600;
        font-size: 16px;
        line-height: 24px;
        color: var($public-title-color);
        word-break: break-all;
    }

    .main-box {
        flex-grow: 1;
        display: flex;
        flex-direction: row;
        align-items: flex-start;



        .left-text .text {
            display: -webkit-box;
            -webkit-box-orient: vertical;
            -webkit-line-clamp: 3;
            overflow: hidden;
            text-overflow: ellipsis;
            color: #8A919F;
            margin-bottom: 6px;
            height: 66px;
            font-size: 13px;
            line-height: 22px;

        }

        .right-img {
            width: 108px;
            flex: 0 0 auto;
            margin-left: 8px;
            margin-right: 8px;
            height: 72px;
            display: block
        }

        .right-img img {
            width: 100%;
            height: 100%;
            border-radius: 4px;
        }
    }
}

.active-row {
    background: #eaf0f0;
    transition: 2s linear;



}

.bg-active{
    background-color: #ededed;
}

.center {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 500px;
}
</style>